package com.muyan.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串解析常用工具
 */
public class RegexUtil {

    public static String filter(String str, String pattern) {
        if (str == null || pattern == null) return str;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            if (str.substring(i, i + 1).matches(pattern)) {
                sb.append(str.charAt(i));
            }
        }
        return sb.toString();
    }

    /**
     * 保留中文字符
     */
    public static String retainChinese(String str) {
        return filter(str, "[\\u4e00-\\u9fbf]+");
    }

    /**
     * 返回第一个匹配的第一组
     */
    public static String getMatchStr(String src, String pattern) {
        MatchResult mr = getMatchResult(src, pattern);
        if (null == mr) return null;
        return mr.group(1);
    }

    /**
     * 返回所有匹配的第一组
     */
    public static List<String> getMatchStrs(String src, String pattern) {
        List<MatchResult> mrs = getMatchResults(src, pattern);
        if (null == mrs) return null;
        List<String> r = new ArrayList<>();
        for (MatchResult mr : mrs) {
            r.add(mr.group(1));
        }
        return r;
    }

    /**
     * 返回第一个匹配
     */
    public static MatchResult getMatchResult(String src, String pattern) {
        if (StrUtil.isBlank(src) || pattern == null) return null;
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(src);
        return matcher.find() ? matcher.toMatchResult() : null;
    }

    public static List<MatchResult> getMatchResults(String src, String pattern) {
        if (StrUtil.isBlank(src) || pattern == null) return null;
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(src);
        List<MatchResult> r = new ArrayList<>();
        while (matcher.find()) {
            r.add(matcher.toMatchResult());
        }
        return r;
    }

}
